<template>
  <div class="app-container" v-loading="loadings">
    <!-- 查询模块 -->
    <div class="formDiv">
      <el-form ref="form" :inline="true" label-width="140px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目ID">
              <el-input v-model="form.projectId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目分类">
              <el-cascader
                v-model="cates"
                placeholder="请选择"
                :options="cateOption"
                change-on-select
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="医院名称">
              <el-input v-model="form.hospital" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目类型">
              <el-select v-model="form.projectType" placeholder="请选择">
                <el-option
                  v-for="item in classOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目是否上架">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="首页推荐">
              <el-select v-model="form.isDashboard" placeholder="请选择">
                <el-option
                  v-for="item in isOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="美学设计师预约状态">
              <el-select v-model="form.selectAppointmentStatus" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input v-model="form.keyword" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目添加时间">
              <el-date-picker
                v-model="dates"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- <el-form-item> -->
            <el-button style="margin-left:60px" type="primary" @click="searchFn">查询</el-button>
            <el-button
              v-if="hasPermission('AdminBeautyProjectProvider.insertProject')"
              type="primary"
              @click="toRoutes('itemAdd')"
            >新增</el-button>
            <!-- AdminReportProvider.exportProjectList -->
            <el-button
              style="margin-left:30px"
              type="primary"
              @click="exfun"
              v-if="$store.state.user.permissionJson.indexOf('AdminReportProvider.exportProjectList') !=-1"
            >导出</el-button>
            <el-upload
              style=" display: inline-block;"
              action
              class="upload-demo"
              :http-request="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="myHeaders"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 主页列表 -->
    <div class="listDiv">
      <!-- table列表 -->
      <el-table
        :data="tableData"
        class="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="selectable"></el-table-column>

        <el-table-column prop="projectId" label="项目ID" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="categoryName" label="项目分类" />
        <el-table-column label="项目类型">
          <template slot-scope="scope">
            <div>{{ scope.row.projectType | cateFn }}</div>
          </template>
        </el-table-column>
        <el-table-column label="项目图片">
          <template slot-scope="scope">
            <div>
              <img style="height:40px;width:40px" :src="scope.row.image | imgUrlFn" alt />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="项目医院">
          <template slot-scope="scope">
            <div
              style="color:#409EFF;cursor:pointer"
              @click="toRoutes('hospitalIndex',scope.row.hospitalName)"
            >{{ scope.row.hospitalName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" sortable label="排序" />
        <el-table-column prop="projectPrice" sortable label="项目价格" />
        <el-table-column prop="originPrice" sortable label="市场价" />
        <el-table-column prop="discounts" sortable label="优惠价" />
        <el-table-column prop="appointmentPrice" sortable label="预约金" />
        <el-table-column prop="deductionCredit" label="抵扣金币">
          <template slot-scope="scope">
            <span
              v-if="scope.row.deductionCredit"
            >{{scope.row.deductionMethod==0?'不抵扣':scope.row.deductionMethod==1?'抵扣金币:':'抵扣银币:'}}{{scope.row.deductionMethod==0?'':scope.row.deductionCredit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentPeoples" sortable label="项目预约量" />
        <el-table-column prop="realPeoples" label="真实预约量" />
        <el-table-column prop="star" label="评星" />
        <el-table-column prop="createdAt" label="项目添加时间" />
        <el-table-column label="是否上架">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              class="switchStyle"
              active-color="#13ce66"
              inactive-color="#eee"
              :active-value="'0'"
              :inactive-value="'1'"
              @click.native="changeStatus(scope.row.projectId,'status',scope.row.status)"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column
                    label="是否秒杀"
                >
                    <template slot-scope="scope">
                        <el-switch
                        class="switchStyle"
                        v-model="scope.row.isPush"
                        @click.native="changeStatus(scope.row.projectId,'isPush',scope.row.isPush)"
                        active-color="#13ce66"
                        inactive-color="#eee"
                        :active-value="'0'"
                        :inactive-value="'1'">
                        </el-switch>
                    </template>
        </el-table-column>-->
        <el-table-column label="首页推荐">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isDashboard"
              class="switchStyle"
              active-color="#13ce66"
              inactive-color="#eee"
              :active-value="'1'"
              :inactive-value="'0'"
              @click.native="changeStatus(scope.row.projectId,'isDashboard',scope.row.isDashboard)"
            />
          </template>
        </el-table-column>
        <el-table-column label="美学设计师预约状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.serverAppointmentStatus"
              class="switchStyle"
              active-color="#13ce66"
              inactive-color="#eee"
              :active-value="'0'"
              :inactive-value="'1'"
              @click.native="changeStatus(scope.row.projectId,'serverAppointmentStatus',scope.row.serverAppointmentStatus)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="hasPermission('AdminBeautyProjectProvider.updateProject')"
              type="text"
              size="small"
              @click="toRoutes('itemEdit',scope.row.projectId)"
            >编辑</el-button>
            <el-button
              v-if="hasPermission('AdminBeautyProjectProvider.findProjectByProjectId')"
              type="text"
              size="small"
              @click="toRoutes('itemInfo',scope.row.projectId)"
            >详情</el-button>
            <el-button
              v-if="hasPermission('AdminBeautyProjectProvider.delProject')"
              type="text"
              size="small"
              @click="deleteFn(scope.row.projectId)"
            >删除</el-button>
            <el-button
              v-if="hasPermission('AdminBeautyProjectProvider.insertProject')"
              type="text"
              size="small"
              @click="copyfn('itemEdit',scope.row.projectId)"
            >复制</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagesCon">
        <div>
          <el-pagination
            :current-page="form.pageNum"
            :page-sizes="page_sizes"
            :page-size="form.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page_totals"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-dialog
      title="以下项目ID因不匹配导入规则，没有导入项目列表，请修改后重新导入"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="messagecopy" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          class="bar_btn copy_btn"
          :data-clipboard-text="messagecopy"
          @click="copy"
        >复制</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  findProjectList,
  updateStatus,
  delProject,
  MmkTagsList,
} from "@/api/itemList";
//E:\中台\middleground-service\src\utils\session.js
import session from "@/utils/session";
import { findAllBeautyCategoryList } from "@/api/medicalClassifyList";
import { policy } from "@/api/policy";
import { exportfile, exportfun } from "@/api/commjs/exprot";
import Clipboard from "clipboard";
import axios from "axios";
export default {
  name: "ItemIndex",
  filters: {
    imgUrlFn: function (e) {
      return localStorage.getItem("imgUrlPrefix") + e;
    },
    cateFn(e) {
      if (e == 0) {
        return "预约项目";
      }
      if (e == 1) {
        return "全额购买项目";
      }
    },
  },
  data() {
    return {
      fileList: [],
      myHeaders: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      mmkTags: null,
      dialogVisible: false,
      mmkTagsOptions: [],
      loadings: true,
      dataFlag: false,
      tableLoading: true,
      dates: "",
      value1: "",
      options: [
        {
          value: "0",
          label: "可预约",
        },
        {
          value: "1",
          label: "不可预约",
        },
      ],
      statusOptions: [
        {
          value: "0",
          label: "上线",
        },
        {
          value: "1",
          label: "下线",
        },
        {
          value: "2",
          label: "回收站",
        },
      ],
      classOptions: [
        {
          value: "0",
          label: "预约项目",
        },
        {
          value: "1",
          label: "全额购买项目",
        },
      ],
      isOptions: [
        {
          value: "0",
          label: "否",
        },
        {
          value: "1",
          label: "是",
        },
      ],
      cates: [],
      form: {
        ispc: 1,
        pageNum: 1,
        pageSize: 10,
        name: null,
        projectId: null,
        cate: null,
        hospital: null,
        projectType: null,
        status: null,
        isPush: null,
        isDashboard: null,
        serverAppointmentStatus: null,
        beginDate: null,
        endDate: null,
        date: null,
        sortKey: null,
        sortType: null,
      },
      tableData: [],
      page_sizes: [10, 30, 50, 100],
      page_totals: 60,
      listForm: {
        pageNum: 1,
        pageSize: 10,
      },
      cateOption: [],
      checarr: [],
      multipleSelection: [],
      messagecopy: "",
    };
  },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.form);
    session.update(keyname, value);
    next();
  },
  watch: {
    checarr(val) {
      console.log(val);
      if (val.length == 3) {
        this.loadings = false;
        this.addcates();
      }
    },
  },
  created() {
    if (session.get(this.$route.name)) {
      this.form = JSON.parse(session.get(this.$route.name));
    }

    this.cateOption = window.helper.cateType("listReturn");
  },
  mounted() {
    this.getList(this.form);
    // this.cateFn('0')
    // if(this.cateFn('0')!=[]){
    this.cateOption[0]["children"] = this.cateFn("0");
    // }
    // if(this.cateFn('1')!=[]){
    this.cateOption[1]["children"] = this.cateFn("1");
    // }
    // if(this.cateFn('2')!=[]){
    this.cateOption[2]["children"] = this.cateFn("2");
    // }
  },
  methods: {
    //导出
    async exfun() {
      this.form.createdBy = this.$store.state.user.name;
      let res = await exportfun(
        "/com.mmk.report.api.AdminReportProvider/1.0.0/exportProjectList.html",
        this.form,
        0,
        1
      );
      console.log(res);
      this.$message.warning(res.data.msg);
    },
    selectable(row, index) {
      //    console.log(row)
      if (row.projectType == "1") {
        return true;
      } else {
        return false;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
      let prodid = [];
      val.map((res) => {
        prodid.push(res.projectId);
      });
      this.form.projectIds = prodid;
    },
    upload(e) {
      let imgFile = e.file; //取到上传的图片
      let formData = new FormData(); //通过formdata上传
      formData.append("dir", "brand");
      formData.append("filename", imgFile);
      axios.defaults.headers["Authorization"] =
        "Bearer " + localStorage.getItem("token");
      axios
        .post("http://adminmping.yuepinyuemei.com/import/import", formData, {
          "Content-Type": "multipart/form-data",
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.messagecopy = "";
            this.getList(this.form);
            if (res.data.data) {
              res.data.data.map((res) => {
                this.messagecopy += res + "\r\n";
              });

              this.dialogVisible = true;
            }
          }
          this.$message.warning(res.data.msg);
        })
        .catch((res) => {
          //  reject(res);
        });
    },
    copy() {
      var clipboard = new Clipboard(".copy_btn");
      // console.log(111);
      clipboard.on("success", (e) => {
        let instance = this.$message.warning("复制成功");
        // console.log(222);
        // 释放内存
        clipboard.destroy();
      });

      clipboard.on("error", (e) => {
        // 不支持复制
        let instance = this.$message.warning("该浏览器不支持自动复制");

        // 释放内存
        clipboard.destroy();
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    addcates() {
      // this.$store.dispatch('addcates', this.cateOption)
      localStorage.setItem("cate", JSON.stringify(this.cateOption));
    },
    // 按钮权限
    hasPermission(e) {
      return window.helper.hasPermission(e);
    },
    handleSortChange(val) {
      const str = val.prop;
      var temp = str.replace(/[A-Z]/g, function (match) {
        return "_" + match.toLowerCase();
      });
      if (temp.slice(0, 1) === "_") {
        // 如果首字母是大写，执行replace时会多一个_，这里需要去掉
        temp = temp.slice(1);
      }
      this.form.sortKey = temp;
      if (val.order == "ascending") {
        this.form.sortType = "asc";
      } else {
        this.form.sortType = "desc";
      }
      // console.log(this.form)
      this.getList(this.form);
    },
    // 获取分类
    cateFn(e) {
      const datas = {
        plate: e,
      };
      const newArr = [];

      findAllBeautyCategoryList(datas).then((res) => {
        if (res.data.code == 0) {
          this.checarr.push(1);
        }
        const resData = res.data.data.list;
        if (resData != []) {
          resData.forEach((item1, index) => {
            newArr.push({
              value: item1.id,
              label: item1.name,
            });
            if (item1.children != null) {
              newArr[index]["children"] = [];
              item1.children.forEach((item2, i) => {
                newArr[index]["children"].push({
                  value: item2.id,
                  label: item2.name,
                });
                if (item2.children != null) {
                  newArr[index]["children"][i]["children"] = [];
                  item2.children.forEach((item3) => {
                    newArr[index]["children"][i]["children"].push({
                      value: item3.id,
                      label: item3.name,
                    });
                  });
                }
              });
            }
          });
        }
      });
      return newArr;
    },
    // 成功状态弹窗
    succStatus(txt) {
      this.$message({
        message: txt + "成功",
        type: "success",
      });
    },
    // 失败状态弹窗
    errorStatus(txt) {
      this.$message.error(txt + "失败");
    },
    // 路由跳转
    toRoutes(e, userId, cateOption) {
      const route = {
        name: e,
        query: { userId: userId, cates: this.cateOption },
      };
      // console.log(route)
      this.$router.push(route);
    },
    copyfn(e, userId) {
      this.$router.push({
        name: e,
        query: { userId: userId, typeName: "copy" },
      });
    },
    // 查询
    searchFn() {
      this.form.pageNum = 1;
      if (this.dates.length > 0) {
        this.form.beginDate = this.dates[0];
        this.form.endDate = this.dates[1];
      }
      this.form.cate = this.cates.join("/");
      console.log(this.form);
      this.getList(this.form);
    },
    // 上下架与状态修改
    changeStatus(projectId, type, status) {
      const datas = {
        projectId: projectId + "",
      };
      console.log(datas);
      datas[type] = status + "";
      updateStatus(datas).then((res) => {
        console.log(res);
        if (res.data.code === 0) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
        } else {
          this.$message.error("修改失败");
        }
      });
      // console.log(datas)
    },
    // 列表数据获取
    getList(e) {
      const datas = e;
      findProjectList(datas)
        .then((res) => {
          console.log(res);
          if (!res.data.code) {
            console.log(res);
            this.tableData = res.data.data.list;
            this.page_totals = res.data.data.count;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    // 删除
    deleteFn(e) {
      // console.log(e)
      const datas = {
        id: e,
      };
      this.$confirm("删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delProject(datas)
            .then((res) => {
              // console.log(res)
              if (!res.data.code) {
                this.succStatus("删除");
                this.getList(this.listForm);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 改变页面条数
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getList(this.form);
    },
    // 选择页数
    handleCurrentChange(val) {
      this.form.pageNum = val;
      this.getList(this.form);
    },
  },
};
</script>
<style scoped>
/* 分页 */
.pagesCon {
  height: 40px;
  margin-top: 20px;
}
.pagesCon > div {
  float: right;
}
/* 表单样式修改 */
.el-range-editor--medium.el-input__inner {
  width: 236px;
}
</style>
